<?php
/**
 * @Author: liuhongbin
 * @Email: 514660094@qq.com
 * @Date: 2019-02-12 16:15:10
 * @Description:
 * @LastEditors: liuhongbin
 * @LastEditTime: xxx
 */

namespace addons\gs_developer\model\Addons;

use addons\gs_developer\model\DevBaseModel;
use think\facade\Db;

class VersionModel extends DevBaseModel
{
    protected $name = self::NAME_PREFIX . 'addons_version';

    public $type = array(
        'install_sql' => 'json',
        'upgrade_sql' => 'json',
        'pack'        => 'json',
        'encrypt'     => 'json',
        'publish'     => 'json'
    );

    public function getAddonAttr($val, $data)
    {
        return (new AddonsModel())->where(['id' => $data['aid']])->find();
    }

    public function replacePlugin($path, $version)
    {
        $plugin = file_get_contents($path);
        $name = $version->addon['name'] ?? '';
        $title = $version->addon['title'] ?? '';
        $description = $version->addon['desc'] ?? '';
        $author = $version->addon['author'] ?? '';
        $version_number = $version['number'] ?? '';

        // 正则替换
        $plugin = preg_replace("/'name'\s*=>\s*'.*?'/", "'name' => '{$name}'", $plugin);
        $plugin = preg_replace("/'title'\s*=>\s*'.*?'/", "'title' => '{$title}'", $plugin);
        $plugin = preg_replace("/'description'\s*=>\s*'.*?'/", "'description' => '{$description}'", $plugin);
        $plugin = preg_replace("/'author'\s*=>\s*'.*?'/", "'author' => '{$author}'", $plugin);
        $plugin = preg_replace("/'version'\s*=>\s*'.*?'/", "'version' => '{$version_number}'", $plugin);

        $drop_sql = (new AddonsModel())->getDropTableSql($name);
        $pattern = "/public function uninstall\(\)\s*{\s*.*?\s*}/";
        $replacement = "public function uninstall(){\r\n\r\n        // 删除当前应用相关的数据表\r\n\r\n        dk_query(\"" . $drop_sql . "\");\r\n    }";
        $plugin = preg_replace($pattern, $replacement, $plugin);
        file_put_contents($path, $plugin);
    }
}
